<template>
  <div class="pagss" @contextmenu.prevent="handleRightClick">
    <div style="height: 20px;"></div>
    <Navvz></Navvz>
    <el-row>
      <el-col :span="24">
        <div class="panel-group1">
          <div class="row_a_c mb_20">
            <div class=" f_24 f_bold">工单列表</div>
            <!-- <div>（注：提交工单是最快速的解决办法）</div> -->

            <div class="color_3FC1C9 ml10"><i class="el-icon-warning-outline mr_5"></i>（注：提交工单是最快速的解决办法）</div>

            <!-- <div>{{message}}</div> -->
          </div>

          <el-form :model="queryParams" :rules="rules" ref="queryForm" label-width="100px" class="demo-ruleForm">
            <div class="row " style="margin-left: -16px;">

              <el-form-item class="itembox box2" label="工单编号：">
                <el-input clearable v-model="queryParams.filter.order_number"></el-input>
              </el-form-item>


              <el-form-item label="工单状态：" class="itembox">
                <el-select clearable v-model="queryParams.filter.state" placeholder="请选择">
                  <el-option label="等待分配专员" value="1"></el-option>
                  <el-option label="正在处理" value="2"></el-option>
                  <el-option label="等待用户反馈" value="3"></el-option>
                  <el-option label="等待技术反馈" value="4"></el-option>
                  <el-option label="已完结" value="5"></el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="操作时间">
                <el-date-picker v-model="dateRange" size="small" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
              </el-form-item>

              <el-button style="height: 36px;width: 86px;" type="primary" @click="handleQuery">查询</el-button>
              <el-button style="height: 36px;width: 86px;" @click="resetQuery">清空</el-button>
            </div>
          </el-form>

          <el-button type="primary" class="mb_20" @click="gdAdd">工单提交</el-button>

          <el-table :data="tableData" style="width: 100%" :row-class-name="tableRowClassName" v-loading="loading">
            <el-table-column prop="ulid" label="工单ID" align="center"></el-table-column>
            <el-table-column prop="order_number" label="工单编号" align="center"></el-table-column>
            <el-table-column prop="title" label="问题描述" align="center"></el-table-column>

            <el-table-column prop="type" label="问题分类" align="center">
              <template slot-scope="scope">

                {{ scope.row.type.title }}
              </template>
            </el-table-column>

            <el-table-column prop="contact_person" label="提交账号" align="center"></el-table-column>

            <el-table-column prop="created_at" label="提交时间" align="center"></el-table-column>


            // 1等待分配专员 2正在处理 3等待用户反馈 4等待技术反馈 5已完结
            <el-table-column label="状态" prop="state">
              <template slot-scope="scope">
                <div v-if="scope.row.state==1" class="ddfbzy center">等待分配专员</div>
                <div v-if="scope.row.state==2" class="zzcl center">正在处理</div>
                <div v-if="scope.row.state==3" class="yhfk center">等待用户反馈</div>
                <div v-if="scope.row.state==4" class="zzcl center">等待技术反馈</div>
                <div v-if="scope.row.state==5" class="ywj center">已完结</div>
              </template>
            </el-table-column>

            <el-table-column label="操作" align="center" width="350px">
              <template slot-scope="scope">
                <!-- <el-button size="mini" type="primary" @click="handleUpdate(scope.row)">查看</el-button> -->
                <el-button size="mini" v-if="scope.row.state==2 || scope.row.state==3 || scope.row.state==4" type="primary" @click="handleAbility(scope.row)">沟通</el-button>
                <el-button size="mini" v-if="scope.row.state!=5" type="primary" @click="handleEnd(scope.row)">完结</el-button>
                <el-button size="mini" v-if="scope.row.state==5 && !scope.row.evaluate_state" type="primary" @click="handleEvaluate(scope.row)">评价</el-button>
                <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>

          </el-table>


          <pagination v-show="total>0" :total="total" :page.sync="queryParams.noPage" :limit.sync="queryParams.pageSize" @pagination="getList" />


        </div>
      </el-col>
    </el-row>


    <el-dialog center :title="title" :visible.sync="open" width="38%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" label-position="left">

        <el-form-item label="问题标题" prop="title" align="right">
          <el-input v-model="form.title" placeholder="请输入" />
        </el-form-item>

        <el-form-item label="问题分类" prop="type">
          <el-select v-model="form.type" placeholder="请选择">
            <el-option v-for="item in questionList" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>


        <el-form-item label="问题描述" prop="detail">
          <el-input :rows="4" v-model="form.detail" type="textarea" placeholder="请输入"></el-input>
        </el-form-item>


        <el-form-item label="问题截图">
          <el-upload :action="upload_url" :headers="headers" list-type="picture-card" :on-success="handleChangePho" :file-list="phoFiles" :on-remove="handleRemovePho" :show-file-list="true">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>

        <el-form-item label="上传附件">
          <el-upload class="upload-demo" :action="upload_url" :on-remove="handleRemove" :on-change="handleChange" :file-list="fileList">
            <el-button size="small" type="primary">点击上传</el-button>

          </el-upload>
        </el-form-item>


        <el-form-item label="联系人姓名">
          <el-input v-model="form.contactPerson" placeholder="请输入" />
        </el-form-item>

        <el-form-item label="联系人电话">
          <el-input v-model="form.contactPhone" placeholder="请输入" />
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input :rows="4" v-model="form.remark" type="textarea" placeholder="请输入"></el-input>
        </el-form-item>

      </el-form>

      <div slot="footer" class="dialog-footer center" v-if="!ulid">

        <div class="quxiao">
          <el-button style="width: 200px;height: 40px;margin-right: 30px;" @click="cancel">取消</el-button>
        </div>

        <el-button style="width: 200px;height: 40px;" type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>



    <communicate ref="childRef"></communicate>

    <el-dialog center title="请为此次服务评分~" :visible.sync="open_evaluate" width="15%" class="center">

      <div class=" column center">

        <div>
          <el-rate v-model="feng"></el-rate>
        </div>

        <div class="mt_30">
          <el-button style="width: 160px;" class="center" type="primary" @click="submitFormpf">确 定</el-button>
        </div>

      </div>

    </el-dialog>

  </div>
</template>

<script>
  import CountTo from 'vue-count-to'
  import Cookies from 'js-cookie'
  import Vue from 'vue';
  import Navvz from "@/components/Navvz";
  import Sidebartss from "@/components/Sidebartss";
  import * as Work from "@/api/operation/work";
  import MD5 from 'md5';
  import Communicate from "./communicate"



  import * as Auth from '@/utils/auth';
  export default {
    name: 'Index',
    components: {
      CountTo,
      Navvz,
      Sidebartss,
      Communicate

    },
    data() {
      return {
        client_id: '',
        messageInput: '', //我发送的消息
        message: '',
        // 总条数
        total: 0,
        feng: null, //评分分值
        open_evaluate: false,
        title: '',
        ulid: '',
        userId: '',
        nickname: '',
        questionList: [], //问题列表
        headers: Auth.getHeader(),
        upload_url: process.env.VUE_APP_BASE_URL + '/file/upload',
        upload_url_all: process.env.VUE_APP_BASE_URL + '/file/uploadAll',
        headers: Auth.getHeader(),
        form: {

        },
        opengt: false,
        open: false, //工单显示
        // fileList: [],
        fileList: [],


        loading: false,
        phoFiles: [],
        currentPage4: 1, //当前页
        time_value: '',
        imageUrl: '',
        // 查询参数
        queryParams: {
          noPage: 1,
          pageSize: 10,
          filter: {
            order_number: null,
            state: null,
            time: null,
          },
          // order_number: undefined,
          // state: undefined,
        },
        // 日期范围
        dateRange: [],
        // dateRange: ["2023-11-12", "2023-11-12 23:59:59"],

        tableData: [],

        // 表单校验
        rules: {
          title: [{
            required: true,
            message: "问题标题不能为空",
            trigger: "blur"
          }],
          type: [{
            required: true,
            message: '请选择问题分类',
            trigger: 'change'
          }],
          detail: [{
            required: true,
            message: '问题详情描述不能为空',
            trigger: 'change'
          }],
        },



      }
    },
    created() {

      var today = new Date();
      var year = today.getFullYear(); //获取年份
      var month = today.getMonth() + 1; //获取月份
      var day = today.getDate(); //获取日期
      var nowdate = year + "-" + month + "-" + day;
      // var nowdatet = nowdate+" 23:59:59"

      this.dateRange.push(nowdate)
      this.dateRange.push(nowdate)
      console.log('abc', this.dateRange)



      // 读取缓存
      this.nickname = localStorage.getItem('username')
      this.userId = localStorage.getItem('user_id')

      // 创建 WebSocket 连接
      // this.socket = new WebSocket('ws://kf.gm.biqihuyu.net:2346');
      this.socket = new WebSocket('wss://kf.biqihuyu.com:2346');
      localStorage.setItem('message_show', 0)

      // 监听 WebSocket 事件
      this.socket.onopen = () => {
        console.log('WebSocket 连接已打开-workSub');
      };

      this.socket.onmessage = (event) => {
        localStorage.setItem('message_show', 0)
        this.message_show = false;
        // alert(222)
        // location.reload();
        // this.$router.go(0);
        // window.location.href = window.location.href;
        this.message = event.data; // 接收到的消息
        var message_items = JSON.parse(this.message)
        console.log('socket_message_items', message_items)

        if (message_items.type == 'init') {
          this.client_id = message_items.client_id
          this.binding();
        }

        if (message_items.type == 'message') {
          if (message_items.info.type == 2) {
            localStorage.setItem('message_show', 1)
            this.playSound();


          }
          this.tableData.map((item) => {
            if (item.ulid == message_items.info.work_order) {
              item.state = message_items.order_work_state
            }
          });
          this.$refs.childRef.childWebSocket(message_items.info);
        }

      };

      this.socket.onclose = () => {
        console.log('WebSocket 连接已关闭');
      };

      this.socket.onerror = (error) => {
        console.error('WebSocket 错误:', error);
      };


      this.getList();
      this.getWorkOrderList(); //获取工单分类列表
    },
    beforeDestroy() {
      // 关闭 WebSocket 连接
      this.socket.close();
    },
    mounted() {

    },
    methods: {

      handleRightClick(event) {
        event.preventDefault(); // 阻止默认行为（这里是刷新页面）
        this.$modal.msgSuccess('页面刷新成功');
        this.getList();
        // 可以在这里添加自定义逻辑，比如显示自定义右键菜单
      },
      playSound() {
        console.log('workSub358');
        this.$emit('work-sub');
        const audio = new Audio('https://bqresoffical.oss-cn-hangzhou.aliyuncs.com/uploads/2024_04_15/7d6412cd9fdc39bc5eaec61fb4cb9b7c.mp3');
        audio.play();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.dateRange = [];
        this.queryParams.filter.order_number = null,
          this.queryParams.filter.state = null,
          this.queryParams.filter.time = null,
          this.handleQuery();
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.noPage = 1;
        this.getList();
      },
      sendMessage() {
        this.socket.send(this.messageInput); // 发送消息
      },

      /** 评价按钮操作 */
      handleEvaluate(row) {
        this.feng = null
        this.ulid = row.ulid
        this.open_evaluate = true;
      },


      /** 评分提交按钮 */
      submitFormpf: function() {
        var peres = {};
        peres.workOrder = this.ulid
        peres.star = this.feng
        peres.type_pj = 1


        Work.evaluate(peres).then(response => {
          this.$modal.msgSuccess('新增成功');
          this.open_evaluate = false;
          this.getList();
        });
      },


      //绑定客户端
      binding() {
        var peres = {}
        peres.client = this.client_id
        peres.user = this.userId
        peres.type_pj = 1
        Work.Binding(peres).then((response) => {
          console.log('binding-workSub', response.data)
        });
      },


      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        this.title = '工单详情'
        this.ulid = row.ulid
        var peres = {};


        peres.workOrder = row.ulid
        peres.type_pj = 1
        Work.Show(peres).then(response => {
          this.form.title = response.data.info.title;
          this.form.type = response.data.info.type.ulid;
          this.form.detail = response.data.info.detail;
          this.form.contactPerson = response.data.info.contact_person;
          this.form.contactPhone = response.data.info.contact_phone;
          this.form.remark = response.data.info.remark;
          var _this = this;
          if (response.data.info.screenshot) {
            response.data.info.screenshot.forEach(function(item, index) {
              var per = {
                url: item
              }
              _this.phoFiles.push(per)
            });
          }
          if (response.data.info.attachment) {
            response.data.info.attachment.forEach(function(item, index) {
              var per = {
                name: '文件' + (index + 1),
                url: item
              }
              _this.fileList.push(per)
            });
          }
          this.open = true;
        });
      },


      /** 沟通按钮操作 */
      handleAbility(row) {

        this.$refs.childRef.childMethod(row);

        // this.reset();
        // this.opengt = true;
        // var peres = {};
        // peres.workOrder = row.ulid

        // var per = this.splicingParameter(peres);
        // Work.Show(per).then(response => {

        // });
      },



      // 表单重置
      reset() {
        this.fileList = [];
        this.phoFiles = [];
        this.form = {};
        this.resetForm("form");
      },

      /** 查询数据库配置列表 */
      getList() {

        this.queryParams.user = this.userId
        this.queryParams.organization = this.userId
        this.queryParams.type_pj = 1

        if (this.dateRange !== null && this.dateRange.length !== 0) {
          // this.dateRange[1] =  this.dateRange[1] +' 23:59:59'
          var time = [];
          time.push(this.dateRange[0]);
          // time.push(this.dateRange[1] + ' 23:59:59');
          time.push(this.dateRange[1]);

          this.queryParams.filter.time = time;
        }
        this.loading = true;
        Work.getList(this.queryParams).then(response => {
          this.tableData = response.data.list;
          this.total = response.data.pagination.totalCount;
          this.loading = false;
        });
      },


      //获取工单分类列表-总接口获取
      getWorkOrderList() {
        this.loading = true;
        var peres = {}
        peres.type_pj = 1
        Work.List(peres).then((response) => {
          this.questionList = response.data.list
          console.log('aaa', response.data.list)
          this.loading = false;
        });
      },

      /** 删除按钮操作 */
      handleDelete(row) {
        var peres = {};
        peres.workOrder = row.ulid
        peres.type_pj = 1
        this.$modal.confirm('是否确认删除').then(function() {
          return Work.Delete(peres);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },


      /** 完结按钮操作 */
      handleEnd(row) {
        var peres = {};

        peres.workOrder = row.ulid
        peres.type_pj = 1

        this.$modal.confirm('是否确认完结').then(function() {
          return Work.Finish(peres);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("成功");
        }).catch(() => {});
      },


      /** 提交按钮 */
      submitForm: function() {
        this.$refs['form'].validate(valid => {
          if (valid) {

            const loading = this.$loading({
              lock: true,
              text: '请稍后.....',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.7)'
            });
            if (this.form.id != undefined) {
              this.form.type_pj = 1;
              Work.Update(this.form).then(response => {
                this.$modal.msgSuccess('修改成功');
                this.open = false;
                this.getList();
              });
            } else {
              this.form.user = this.userId
              this.form.organization = this.userId
              this.form.type_pj = 1
              this.loading = true;
              Work.Add(this.form).then(response => {
                this.$modal.msgSuccess('新增成功');
                this.open = false;
                this.loading = false;
                loading.close();
                this.getList();
              });
            }
          }
        });
      },



      // 设置photo值--图片上传拼接数据
      phoChange(fileList) {
        let temp_str = '';
        if (fileList.length > 0) {
          for (let i = 0; i < fileList.length; i++) {
            if (fileList[i].response) {
              if (fileList[i].response.code === 200) {
                if (i === 0) {
                  temp_str += fileList[i].response.data;
                } else {
                  // 最终photo的格式是所有已上传的图片的url拼接的字符串（逗号隔开）

                  temp_str += ',' + fileList[i].response.data;
                }
              }
            }
          }
        }

        this.form.screenshot = temp_str.split(',');
      },


      // 设置file值--文件上传拼接数据
      fileChange(fileList) {
        let temp_str = '';
        if (fileList.length > 0) {
          for (let i = 0; i < fileList.length; i++) {
            if (fileList[i].response) {
              if (fileList[i].response.code === 200) {
                if (i === 0) {
                  temp_str += fileList[i].response.data;
                } else {
                  // 最终photo的格式是所有已上传的图片的url拼接的字符串（逗号隔开）

                  temp_str += ',' + fileList[i].response.data;
                }
              }
            }
          }
        }

        this.form.attachment = temp_str.split(',');
      },

      //相册上传成功调用
      handleChangePho(res, file, fileList) {
        this.phoChange(fileList);
      },

      //文件上传成功调用
      handleChange(file, fileList) {
        this.fileChange(fileList);
      },

      // 取消按钮
      cancel() {
        this.open = false;

      },
      //图片移出
      handleRemovePho(file, fileList) {
        this.phoChange(fileList);
        console.log('file', file);
        console.log('fileList', fileList);
      },

      //文件移出
      handleRemove(file, fileList) {
        this.fileChange(fileList);
      },

      //工单提交 按钮
      gdAdd() {
        this.title = '工单提交';
        this.form = {};
        this.ulid = '';
        this.open = true;
        // this.resetForm("form");
        this.reset()

      },

      tableRowClassName({
        row,
        rowIndex
      }) {
        if (rowIndex === 1) {
          return 'warning-row';
        } else if (rowIndex === 3) {
          return 'success-row';
        }
        return '';
      },




      gotoPage(url) {
        this.$router.push(url);
      },



    }
  }
</script>

<style lang="scss" scoped>
  .pagss {
    height: 100%;
    background: #E4EEF9;
    // padding: 5px 0 15px 40px;
  }

  .panel-group1 {
    padding: 25px;
    margin-top: 18px;
    margin-bottom: 0px;
    margin-right: 15px;
    margin-left: 15px;
    min-height: 760px;
    background: #FFFFFF;
    border-radius: 10px 10px 10px 10px;
    opacity: 1;
  }

  .ddfbzy {
    width: 112px;
    height: 32px;
    background: #FFDBDB;
    border-radius: 4px;
  }

  .zzcl {
    width: 112px;
    height: 32px;
    background: #DBE2FF;
    border-radius: 4px;
  }

  .yhfk {
    width: 112px;
    height: 32px;
    color: #FFFFFF;
    background: #306EF2;
    border-radius: 4px;
  }

  .ywj {
    width: 112px;
    height: 32px;
    background: #E3E3E3;
    border-radius: 4px;
  }

  .itembox {
    margin-right: 45px;

  }

  ::v-deep .el-button--primary {
    color: #FFFFFF;
    background-color: #3FC1C9 !important;
    border-color: #3FC1C9 !important;
  }

  ::v-deep .el-button:hover,
  .el-button:focus {
    color: #000000;
    border-color: #A5EDF1;
    background-color: #A5EDF1;
  }

  ::v-deep .el-rate__icon {
    font-size: 38px;
  }
</style>
